import { useRef, useCallback, useContext, useState } from "react";

import { INPUT_BG_COLOR, INPUT_FG_COLOR } from "~/constants";
import { _ } from "~/lib/i18n";
import { loadImage, readAsDataURL } from "~/lib/util";
// @ts-ignore
import { Pixelit } from "~/lib/pixelit.js";
import { ManagerContext } from "~/contexts";

import PrimaryButton from "~/components/PrimaryButton";
import CommentIcon from "~/components/icons/CommentIcon";
import ImageIcon from "~/components/icons/ImageIcon";
import FilePicker from "~/components/FilePicker";
import PostImage from "~/components/PostImage";

const containerStyle = {
  display: "flex",
  flexDirection: "row" as "row",
  justifyContent: "space-between",
  flexWrap: "nowrap" as "nowrap",
  gap: "12px",
  padding: "12px",
  backgroundColor: INPUT_BG_COLOR,
  position: "fixed" as "fixed",
  bottom: 0,
  width: "calc(100% - 24px)",
};

const iconBtnStyle = {
  background: "none",
  color: "white",
  alignSelf: "center",
  padding: "2px",
};

const inputStyle = {
  color: INPUT_FG_COLOR,
  backgroundColor: INPUT_BG_COLOR,
  border: 0,
  outline: 0,
  margin: 0,
  padding: 0,
  flexGrow: 1,
  minWidth: "80px",
};

interface Props {
  postId: string;
}

export default function ReplyDraft({ postId }: Props) {
  const manager = useContext(ManagerContext);
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [imgUrl, setImgUrl] = useState<string>("");

  const onFileSelected = useCallback(
    async (file: File) => {
      let url;
      if (
        file.type.startsWith("image/") &&
        file.type !== "image/png" &&
        file.type !== "image/jpeg" &&
        file.size <= manager.maxSize
      ) {
        url = await readAsDataURL(file);
        console.log("image size:" + url.length);
      } else {
        const blobUrl = URL.createObjectURL(file);
        url = await resizeImage(blobUrl);
        URL.revokeObjectURL(blobUrl);
        console.log("resizeImage:" + url.length);
      }
      setImgUrl(url);
    },
    [setImgUrl],
  );

  async function resizeImage(url: string): Promise<string> {
    const img = await loadImage(url);
    const canvas = document.createElement("canvas");

    const config = {
      to: canvas,
      from: img,
      maxHeight: 500,
      maxWidth: 500,
    };
    new Pixelit(config).draw(); // just resize

    url = canvas.toDataURL("image/jpeg");
    canvas.remove();
    return url;
  }

  const onClick = useCallback(() => {
    if (!inputRef.current) return;
    const text = (inputRef.current.value || "").trim();
    if (!text && !imgUrl) return;
    // @ts-ignore
    manager.reply(postId, text, imgUrl);
    inputRef.current.value = "";
    setImgUrl("");
  }, [postId, inputRef, manager, imgUrl]);

  const handleBlur = useCallback(
    (event: React.FocusEvent<HTMLInputElement>) => {
      // Prevent the input from losing focus
      event.preventDefault();
      inputRef.current!.focus();
    },
    [inputRef],
  );

  const hint = _("Write a comment...");

  return (
    <div style={containerStyle}>
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          flexGrow: 1,
          gap: "8px",
          overflow: "hidden",
        }}
      >
        <input
          ref={inputRef}
          style={inputStyle}
          placeholder={hint}
          type="text"
          onBlur={handleBlur}
        />
        {imgUrl && (
          <div style={{ position: "relative" }}>
            <PostImage 
              src={imgUrl} 
              images={[imgUrl]} 
              index={0}
              onDelete={() => setImgUrl("")} 
            />
          </div>
        )}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            flexShrink: 0,
            gap: "4px",
          }}
        >
          <FilePicker
            accept="image/*"
            onFileSelected={onFileSelected}
            style={iconBtnStyle}
          >
            <ImageIcon
              style={{
                verticalAlign: "middle",
                width: "1.2em",
                height: "auto",
              }}
            />
          </FilePicker>
          <PrimaryButton onClick={onClick} style={{ padding: "5px 10px" }}>
            <CommentIcon style={{ height: "100%" }} />
          </PrimaryButton>
        </div>
      </div>
    </div>
  );
}
